package com.zjjt.dc.modules.datacatch.service.lw.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.Method;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.zjjt.dc.common.util.DESEncryptEntity;
import com.zjjt.dc.common.util.DESEncryptUtil;
import com.zjjt.dc.modules.datacatch.def.ILWConst;
import com.zjjt.dc.modules.datacatch.entity.QueryCondition;
import com.zjjt.dc.modules.datacatch.entity.lw.DcCatchDataLwWh;
import com.zjjt.dc.modules.datacatch.entity.lw.DcCatchDataLwCustomer;
import com.zjjt.dc.modules.datacatch.entity.lw.DcCatchDataLwCustomerHoldings;
import com.zjjt.dc.modules.datacatch.service.IDcCatchDataLwCustomerHoldingsService;
import com.zjjt.dc.modules.datacatch.service.lw.IDcCatchDataLwCustomerService;
import com.zjjt.dc.modules.datacatch.service.lw.IDcDataCatchLwWhService;
import com.zjjt.dc.modules.datacatch.service.lw.ILWDataCatchService;
import com.zjjt.dc.modules.datacatch.template.IExchangeLWTemplate;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Slf4j
@Service
public class LWDataCatchService implements ILWDataCatchService {

    Logger logger = LoggerFactory.getLogger(LWDataCatchService.class);

    @Value("${liao-wen.origin}")
    private String baseUrl;

    @Value("${liao-wen.solder.uid}")
    private String solderId;

    @Value("${liao-wen.solder.pwd}")
    private String solderPwd;

    @Value("${liao-wen.broker.uid}")
    private String brokerId;

    @Value("${liao-wen.broker.pwd}")
    private String brokerPwd;

    @Value("${liao-wen.wh-manager.uid}")
    private String whManagerId;

    @Value("${liao-wen.wh-manager.pwd}")
    private String whManagerPwd;

    @Autowired
    private IDcDataCatchLwWhService dcCatchDataLwWhService;

    @Autowired
    private IDcCatchDataLwCustomerService dcCatchDataLwCustomerService;

    @Autowired
    private IDcCatchDataLwCustomerHoldingsService dcCatchDataLwCustomerHoldingsService;


    @Override
    public int updateWareHouseDatas(QueryCondition condition) {
        try {

//            Calendar now = Calendar.getInstance();
//            Calendar start = Calendar.getInstance();
//            start.add(Calendar.DAY_OF_YEAR, -7); // (不可以超过3个月)
//            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
//            dateFormat.format(new java.util.Date());

            DESEncryptEntity desModel = new DESEncryptEntity();
            desModel.setModel("CBC");
            desModel.setFillCode("pkcs5padding");
            desModel.setOffset("1g6n8n8t");
            desModel.setPassword("1g6n8n8t");
            desModel.setOutType("base64");
            desModel.setOutCharset("utf-8");


            JSONObject requestBody = new JSONObject();
            requestBody.set(IExchangeLWTemplate.NAME, ILWConst.LW_API_O_BILL_APPLY_QUERY)
                    .set(IExchangeLWTemplate.WM_ID, whManagerId)
                    .set(IExchangeLWTemplate.WM_PW, whManagerPwd)
                    .set(IExchangeLWTemplate.START_DATE, condition.getBeginTime())
                    .set(IExchangeLWTemplate.END_DATE, condition.getEndTime())
                    .set(IExchangeLWTemplate.USER_RECEIVE_ID, "")
                    .set(IExchangeLWTemplate.BIZ_ID, "");

            HttpRequest request = new HttpRequest(baseUrl + ILWConst.LW_API_BILL_BASE_URL).setMethod(Method.POST);
            String responseBody = request.body(requestBody.toString()).execute().body();
            JSONObject json = new JSONObject(responseBody);
            JSONObject jsonResult = json.getJSONObject("result");

            if (jsonResult.getLong("RETCODE") < 0) {
                logger.error("获取仓库数据失败: 仓库管理员登录失败");
                return -1001;
            } else {
                int totalCount = jsonResult.getInt(IExchangeLWTemplate.TOTAL_COUNT);
                JSONObject jsonResultList = json.getJSONObject("RESULTLIST");
                JSONArray jsonResultListArray = jsonResultList.getJSONArray("REC");
                logger.info("获取仓库数据成功: " + totalCount + " 条");

                for (int i = 0; i < jsonResultListArray.size(); i++) {
                    JSONObject jsonItem = jsonResultListArray.getJSONObject(i);
                    DcCatchDataLwWh entity = new DcCatchDataLwWh();
                    entity.setCreateBy(1l);
                    entity.setUpdateBy(1l);
                    entity.setExId(jsonItem.getStr(IExchangeLWTemplate.OUT_STOCK_ID));
                    entity.setBillId(jsonItem.getStr(IExchangeLWTemplate.BILL_ID));
                    entity.setExUserId(jsonItem.getStr(IExchangeLWTemplate.USER_RECEIVE_ID));
                    entity.setExUserName(jsonItem.getStr(IExchangeLWTemplate.USER_RECEIVE_NAME));
                    entity.setOriginalId(jsonItem.getStr(IExchangeLWTemplate.ORIGINAL_VOUCHER_ID));
                    entity.setBreedId(jsonItem.getStr(IExchangeLWTemplate.BREED_ID));
                    entity.setBreedName(jsonItem.getStr(IExchangeLWTemplate.BREED_NAME));
                    entity.setWhId(jsonItem.getStr(IExchangeLWTemplate.WAREHOUSE_ID));
                    entity.setWhName(jsonItem.getStr(IExchangeLWTemplate.WAREHOUSE_NAME));
                    entity.setGoodsCount(jsonItem.getStr(IExchangeLWTemplate.COUNT));
                    entity.setGoodsUnit(jsonItem.getStr(IExchangeLWTemplate.UNIT));
                    entity.setDeliveryType(jsonItem.getStr(IExchangeLWTemplate.DELIVERY_TYPE));
                    entity.setDeliveryStatus(jsonItem.getStr(IExchangeLWTemplate.DELIVERY_STATUS));
                    entity.setExCreateTime(jsonItem.getLocalDateTime(IExchangeLWTemplate.CREATE_TIME, LocalDateTime.now()));
                    entity.setExPassTime(jsonItem.getLocalDateTime(IExchangeLWTemplate.PASS_TIME, LocalDateTime.now()));
                    entity.setExpressNo(jsonItem.getStr(IExchangeLWTemplate.EXPRESS_NO));
                    entity.setReceiverName(jsonItem.getStr(IExchangeLWTemplate.RECEIVER_NAME));
                    entity.setReceiverTel(jsonItem.getStr(IExchangeLWTemplate.RECEIVER_TEL));
                    entity.setReceiverAddr(jsonItem.getStr(IExchangeLWTemplate.RECEIVER_ADDRESS));

                    BaseMapper<DcCatchDataLwWh> baseMapper = dcCatchDataLwWhService.getBaseMapper();
                    boolean isExist = baseMapper.exists(new QueryWrapper<DcCatchDataLwWh>().eq("ex_id", entity.getExId()));

                    if (isExist) {
                        DcCatchDataLwWh oldEntity = dcCatchDataLwWhService.getOne(new QueryWrapper<DcCatchDataLwWh>().eq("ex_id", entity.getExId()));
                        if (!StrUtil.equals(oldEntity.getDeliveryStatus(), entity.getDeliveryStatus())) {
                            entity.setId(oldEntity.getId());
                            dcCatchDataLwWhService.updateById(entity);
                        }
                    } else {
                        dcCatchDataLwWhService.save(entity);
                    }
                }
            }

        } catch (Exception e) {
            logger.error("获取仓库数据失败: " + e.getMessage());
            return -1;
        }

        return 0;
    }

    @Override
    public int updateCustomerDatas(QueryCondition condition) {
        try {

            DESEncryptEntity desModel = new DESEncryptEntity();
            desModel.setModel("CBC");
            desModel.setFillCode("pkcs5padding");
            desModel.setOffset("1g6n8n8t");
            desModel.setPassword("1g6n8n8t");
            desModel.setOutType("base64");
            desModel.setOutCharset("utf-8");


            JSONObject requestBody = new JSONObject();
            try {
                requestBody.set(IExchangeLWTemplate.NAME, ILWConst.LW_API_LOGIN)
                        .set(IExchangeLWTemplate.USER_ID, brokerId)
                        .set(IExchangeLWTemplate.USER_PWD, DESEncryptUtil.encrypt(desModel, brokerPwd))
//                    .set(IExchangeLWTemplate.USER_PWD,  "nc1rNyfFNsZo5VVZgMb8mg==")
                        .set(IExchangeLWTemplate.LOGIN_TYPE, "web");
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

            HttpRequest request = new HttpRequest(baseUrl + ILWConst.LW_API_BASE_URL).setMethod(Method.POST);
            String responseBody = request.body(requestBody.toString()).execute().body();
            JSONObject json = new JSONObject(responseBody);
            JSONObject jsonResult = json.getJSONObject("result");
            if (jsonResult.getLong("RETCODE") < 0) {
                logger.error("获取客户数据失败: 经纪会员登录失败");
                return -1001;
            } else {
                JSONObject requestBodyCH = new JSONObject();
                requestBodyCH.set(IExchangeLWTemplate.NAME, ILWConst.LW_API_B_USER_QUERY)
                        .set(IExchangeLWTemplate.USER_ID, brokerId)
                        .set(IExchangeLWTemplate.SESSON_ID, jsonResult.getLong("RETCODE"))
                        .set(IExchangeLWTemplate.BASE_TIME, 0);

                HttpRequest requestCH = new HttpRequest(baseUrl + ILWConst.LW_API_BASE_URL).setMethod(Method.POST);
                String responseBodyCH = requestCH.body(requestBodyCH.toString()).execute().body();
                JSONObject jsonCH = new JSONObject(responseBodyCH);
                JSONObject jsonResultCH = jsonCH.getJSONObject("result");
                if (jsonResultCH.getLong("RETCODE") < 0) {
                    logger.error("获取客户数据失败: 客户查询失败");
                    return -1002;
                } else {
                    JSONArray jsonResultListArray = (JSONArray) JSONUtil.getByPath(jsonCH, "RESULTLIST.REC");
                    // 处理客户持仓数据
                    if (!jsonResultListArray.isEmpty()) {
                        logger.info("获取客户数据成功: " + jsonResultListArray.size() + " 条");
                        // 这里应该添加处理客户持仓数据的逻辑
                        for (Object item : jsonResultListArray) {
                            JSONObject jsonItem = (JSONObject) item;
                            DcCatchDataLwCustomer entity = new DcCatchDataLwCustomer();

//                        entity.setId(IdUtil.getDataCenterId(15));
                            entity.setCreateBy(1l);
                            entity.setUpdateBy(1l);
                            entity.setCustomerCode(jsonItem.getStr(IExchangeLWTemplate.CUSTOMER_CODD));
                            entity.setCustomerName(jsonItem.getStr(IExchangeLWTemplate.CUSTOMER_NAME));
                            entity.setCustomerStatus(jsonItem.getInt(IExchangeLWTemplate.CUSTOMER_STATUS));
                            entity.setIsFrozen(jsonItem.getStr(IExchangeLWTemplate.IS_FROZEN));
                            entity.setOpenTime(jsonItem.getLocalDateTime(IExchangeLWTemplate.OPEN_TIME, LocalDateTime.now()));
                            entity.setIdNumber(jsonItem.getStr(IExchangeLWTemplate.ID_NUMBER));
                            entity.setPhoneNumber(jsonItem.getStr(IExchangeLWTemplate.PHONE_NUMBER));
                            entity.setContactPerson(jsonItem.getStr(IExchangeLWTemplate.CONTACT_PERSON));

                            BaseMapper<DcCatchDataLwCustomer> baseMapper = dcCatchDataLwCustomerService.getBaseMapper();
                            boolean isExist = baseMapper.exists(new QueryWrapper<DcCatchDataLwCustomer>().eq("customer_code", entity.getCustomerCode()));

                            if (isExist) {
                                DcCatchDataLwCustomer oldEntity = dcCatchDataLwCustomerService.getOne(new QueryWrapper<DcCatchDataLwCustomer>().eq("customer_code", entity.getCustomerCode()));
                                entity.setId(oldEntity.getId());
                                dcCatchDataLwCustomerService.updateById(entity);

                            } else {
                                dcCatchDataLwCustomerService.save(entity);
                            }
                        }
                    }
                }

            }
        } catch (Exception e) {
            log.error("新增客户数据失败：{}", e.toString());
        }
        return 0;
    }

    @Override
    public int updateOrderDatas(QueryCondition condition) {
        return 0;
    }

    @Override
    public int updateCustomerHoldings(QueryCondition condition) {
        try {


            DESEncryptEntity desModel = new DESEncryptEntity();
            desModel.setModel("CBC");
            desModel.setFillCode("pkcs5padding");
            desModel.setOffset("1g6n8n8t");
            desModel.setPassword("1g6n8n8t");
            desModel.setOutType("base64");
            desModel.setOutCharset("utf-8");


            JSONObject requestBody = new JSONObject();
            try {
                requestBody.set(IExchangeLWTemplate.NAME, ILWConst.LW_API_LOGIN)
                        .set(IExchangeLWTemplate.USER_ID, solderId)
                        .set(IExchangeLWTemplate.USER_PWD, DESEncryptUtil.encrypt(desModel, solderPwd))
//                    .set(IExchangeLWTemplate.USER_PWD,  "nc1rNyfFNsZo5VVZgMb8mg==")
                        .set(IExchangeLWTemplate.LOGIN_TYPE, "web");
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

            HttpRequest request = new HttpRequest(baseUrl + ILWConst.LW_API_BASE_URL).setMethod(Method.POST);
            String responseBody = request.body(requestBody.toString()).execute().body();
            JSONObject json = new JSONObject(responseBody);
            JSONObject jsonResult = json.getJSONObject("result");
            if (jsonResult.getLong("RETCODE") < 0) {
                logger.error("获取客户持仓数据失败: 客户管理员登录失败");
                return -1001;
            } else {
                JSONObject requestBodyCH = new JSONObject();
                requestBodyCH.set(IExchangeLWTemplate.NAME, ILWConst.LW_API_B_HOLD_QUERY)
                        .set(IExchangeLWTemplate.USER_ID, solderId)
                        .set(IExchangeLWTemplate.SESSON_ID, jsonResult.getLong("RETCODE"));

                HttpRequest requestCH = new HttpRequest(baseUrl + ILWConst.LW_API_BASE_URL).setMethod(Method.POST);
                String responseBodyCH = requestCH.body(requestBodyCH.toString()).execute().body();
                JSONObject jsonCH = new JSONObject(responseBodyCH);
                JSONObject jsonResultCH = jsonCH.getJSONObject("result");
                if (jsonResultCH.getLong("RETCODE") < 0) {
                    logger.error("获取客户持仓数据失败: 客户持仓查询失败");
                    return -1002;
                } else {
                    JSONArray jsonResultListArray = (JSONArray) JSONUtil.getByPath(jsonCH, "RESULTLIST.REC");
                    // 处理客户持仓数据
                    if (!jsonResultListArray.isEmpty()) {
                        logger.info("获取客户持仓数据成功: " + jsonResultListArray.size() + " 条");
                        // 这里应该添加处理客户持仓数据的逻辑
                        for (Object item : jsonResultListArray) {
                            JSONObject jsonItem = (JSONObject) item;
                            DcCatchDataLwCustomerHoldings entity = new DcCatchDataLwCustomerHoldings();

                            entity.setCreateBy(1l);
                            entity.setUpdateBy(1l);
                            entity.setProductCode(jsonItem.getStr(IExchangeLWTemplate.PRODUCT_CODE));
                            entity.setProductName(jsonItem.getStr(IExchangeLWTemplate.PRODUCT_NAME));
                            entity.setHoldingQuantity(jsonItem.getInt(IExchangeLWTemplate.HOLDING_QUANTITY));
                            entity.setAvgInventoryPrice(jsonItem.getBigDecimal(IExchangeLWTemplate.AVG_INVENTORY_PRICE));
                            entity.setOrderFrozenQuantity(jsonItem.getInt(IExchangeLWTemplate.ORDER_FROZEN_QUANTITY));
                            entity.setSaleLimitFrozenQuantity(jsonItem.getInt(IExchangeLWTemplate.SALE_LIMIT_FROZEN_QUANTITY));
                            entity.setDeliveryApplyQuantity(jsonItem.getInt(IExchangeLWTemplate.DELIVERY_APPLY_QUANTITY));
                            entity.setPositionAmount(jsonItem.getBigDecimal(IExchangeLWTemplate.POSITION_AMOUNT));
                            entity.setValueChange(jsonItem.getBigDecimal(IExchangeLWTemplate.VALUE_CHANGE));
                            entity.setSellableQuantity(jsonItem.getInt(IExchangeLWTemplate.SELLABLE_QUANTITY));
                            entity.setAvailableQuantity(jsonItem.getInt(IExchangeLWTemplate.AVAILABLE_QUANTITY));
                            entity.setUserCode(jsonItem.getStr(IExchangeLWTemplate.PERSON_CODE));
                            entity.setUserType(jsonItem.getInt(IExchangeLWTemplate.PERSON_TYPE));
                            entity.setUserName(jsonItem.getStr(IExchangeLWTemplate.PERSON_NAME));
                            entity.setMarketValue(jsonItem.getBigDecimal(IExchangeLWTemplate.MARKET_PRICE));

                            BaseMapper<DcCatchDataLwCustomerHoldings> baseMapper = dcCatchDataLwCustomerHoldingsService.getBaseMapper();
                            boolean isExist = baseMapper.exists(new QueryWrapper<DcCatchDataLwCustomerHoldings>().eq("product_code", entity.getProductCode()).eq("user_code", entity.getUserCode()));

                            if (isExist) {
                                DcCatchDataLwCustomerHoldings oldEntity = dcCatchDataLwCustomerHoldingsService.getOne(new QueryWrapper<DcCatchDataLwCustomerHoldings>().eq("product_code", entity.getProductCode()).eq("user_code", entity.getUserCode()).orderByDesc("create_time"));
                                if (entity.getAvgInventoryPrice().compareTo(oldEntity.getAvgInventoryPrice()) > 0) {
                                    dcCatchDataLwCustomerHoldingsService.save(entity);
                                }

                            } else {
                                dcCatchDataLwCustomerHoldingsService.save(entity);
                            }
                        }
                    }
                }

            }
        }catch (Exception e){
            log.error("数据抓取失败：{}",e.toString());
        }
        return 0;
    }

}
